package com.own.component.util.time;

import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * TimerUtil
 *
 * @author chenxueli
 * @date 2024-01-12 19:30:00
 */
@Slf4j
public class TimerUtil {

    private static final Map<String, Long> TIMER_MAP = new ConcurrentHashMap<>();

    private static final String DEFAULT_KEY = "default";

    /**
     * 计时开始
     */
    public static void start() {
        start(DEFAULT_KEY);
    }

    /**
     * 计时结束
     */
    public static void end() {
        end(DEFAULT_KEY);
    }

    /**
     * 计时开始
     *
     * @param key 计时器key
     */
    public static void start(String key) {
        TIMER_MAP.put(key, System.currentTimeMillis());
    }

    /**
     * 计时结束
     *
     * @param key 计时器key
     */
    public static void end(String key) {
        if (TIMER_MAP.containsKey(key)) {
            log.info("计时器：{}，耗时：{}ms", key, System.currentTimeMillis() - TIMER_MAP.get(key));
        }
    }

    /**
     * 清除计时器
     */
    public static void clear() {
        TIMER_MAP.remove(DEFAULT_KEY);
    }

    /**
     * 清除计时器
     *
     * @param key 计时器key
     */
    public static void clear(String key) {
        TIMER_MAP.remove(key);
    }

}
